from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
import os
import json
import uuid
import tempfile
import dashscope
from openai import OpenAI
try:
    from volcenginesdkarkruntime import Ark
except ImportError:
    try:
        from volcengine.ark import Ark
    except ImportError:
        print("Warning: volcengine SDK not found. Please install it manually if needed.")
from typing import Dict, Any

# ===================== 基础配置 =====================
UPLOAD_FOLDER = os.environ.get("UPLOAD_FOLDER", "uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# DashScope 配置
dashscope.api_key = 'sk-b42f646a808549e099932167d32f2a9c'
DEFAULT_ASR_MODEL = 'qwen-audio-asr'

# Qwen 客户端
client = OpenAI(
    api_key='sk-b42f646a808549e099932167d32f2a9c',
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 允许的音频格式
ALLOWED_EXTS = {'.wav', '.mp3', '.m4a', '.flac', '.aac', '.ogg', '.opus'}

# 创建FastAPI应用
app = FastAPI(title="录音分析API", description="录音文件证据分析接口", version="1.0.0")


def allow_file(filename: str) -> bool:
    """检查文件格式是否允许"""
    return os.path.splitext(filename)[1].lower() in ALLOWED_EXTS


def real_asr(file_path: str) -> str:
    """调用 DashScope ASR，将本地音频转文字"""
    audio_uri = f"file://{os.path.abspath(file_path)}"
    try:
        response = dashscope.MultiModalConversation.call(
            model=DEFAULT_ASR_MODEL,
            messages=[{"role": "user", "content": [{"audio": audio_uri}]}],
            result_format="message"
        )
        text = response['output']['choices'][0]['message']['content'][0]['text']
        return text
    except Exception as e:
        return f"ASR 解析失败: {e}"


def analyze_audio(audio_path: str) -> str:
    """
    分析单个音频文件，返回分析结果
    
    :param audio_path: 音频文件路径
    :return: 分析结果JSON字符串
    """
    # 检查文件格式
    if not allow_file(audio_path):
        raise ValueError(f"文件类型不支持: {audio_path}")
    
    # 音频转写
    asr_text = real_asr(audio_path)
    
    # 系统提示 - 修改为返回中文字段名
    system_prompt = (
        '''
        你是一名劳动法律小助手的智能分析模块，用户提供了音频材料，请分析音频是否可以作为证据以及证据的充分性。只返回JSON格式，包含五个字段：
            1. "文件类型"："录音"
            2. "关键内容摘要"：对录音内容的精确概述
            3. "文件有效性说明"：文件的有效性说明
            4. "与案件关联性分析"：与案件关联性分析
            5. "是否可以作为证据"："是"或"否"
        不要输出其他文字或额外说明。
        '''
    )
    
    user_message = f"音频转写内容:\n{asr_text}"
    
    # 使用豆包推理
    ark_client = Ark(
        base_url="https://ark.cn-beijing.volces.com/api/v3",
        api_key=os.environ.get("ARK_API_KEY", "1b4bef68-37d5-4196-ba8b-17c9054ae9c5")
    )
    
    doubao_messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_message}
    ]
    
    completion = ark_client.chat.completions.create(
        model="doubao-seed-1-6-250615",
        messages=doubao_messages
    )
    
    reply_text = completion.choices[0].message.content
    return reply_text


@app.post("/analyze_recording")
async def analyze_recording(Record_file: UploadFile = File(...)) -> JSONResponse:
    """
    录音分析接口
    
    Args:
        Record_file: 上传的录音文件
    
    Returns:
        JSONResponse: 包含分析结果的JSON响应
    """
    try:
        # 验证文件格式
        if not allow_file(Record_file.filename):
            raise HTTPException(
                status_code=400,
                detail=f"不支持的文件格式。支持的格式: {', '.join(ALLOWED_EXTS)}"
            )
        
        # 创建临时文件保存上传的音频
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(Record_file.filename)[1]) as temp_file:
            # 读取上传文件内容并写入临时文件
            content = await Record_file.read()
            temp_file.write(content)
            temp_file_path = temp_file.name
        
        try:
            # 分析音频文件
            result_text = analyze_audio(temp_file_path)
            
            # 尝试解析返回的JSON
            try:
                result_json = json.loads(result_text)
                return JSONResponse(
                    status_code=200,
                    content=result_json
                )
            except json.JSONDecodeError:
                # 如果返回的不是有效JSON，则包装成错误响应
                return JSONResponse(
                    status_code=500,
                    content={
                        "error": "分析结果格式错误",
                        "raw_result": result_text
                    }
                )
        
        finally:
            # 清理临时文件
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
    
    except HTTPException:
        # 重新抛出HTTP异常
        raise
    except Exception as e:
        # 处理其他异常
        return JSONResponse(
            status_code=500,
            content={
                "error": "服务器内部错误",
                "detail": str(e)
            }
        )


@app.get("/")
async def root():
    """根路径，返回API信息"""
    return {
        "message": "录音分析API服务",
        "version": "1.0.0",
        "endpoints": {
            "/analyze_recording": "POST - 上传录音文件进行分析"
        }
    }


@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8005)